package linhnv.app;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.net.Uri;
import android.sax.StartElementListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ListItemsAdapter extends BaseAdapter {
	List<HashMap<String, String>> list ;
	private Context mContext;
	private static int HEADER =0;
	private int typeDB;	
		public ListItemsAdapter(Context c) {
			Log.d("linhnv","======================come here4");
			mContext=c;
			// TODO Auto-generated constructor stub
		}
		public ListItemsAdapter(Context c,int param)
		{
			mContext=c;
			typeDB= param;
			loadData();
			Log.d("linhnv","======================come here4========"+typeDB);
		}
		public Object getItem(int position) {
		        return null;
	    }

	    public long getItemId(int position) {
	        return 0;
	    }
	    public int getCount() {
	    	if(list == null || list.size() == 0)
	    	{
	    		return 0;
	    	}
			// TODO Auto-generated method stub
			 return list.size()-1;
		}
	    
	   
		public View getView(int position, View convertView, ViewGroup parent) {
	    	View MyView = convertView;
	    	

	        	   
	        	  
	         
	        if ( true )
	        {
	        	
	                               /*we define the view that will display on the grid*/
	        	//Log.d("Linhnv","============================"+ list.size()+"===========position:::"+position );
	           //Inflate the layout
	           LayoutInflater li =(LayoutInflater)mContext.getSystemService
	           (Context.LAYOUT_INFLATER_SERVICE);
	           MyView = li.inflate(R.layout.list_items, null);
	           WebView wv = (WebView)MyView.findViewById(R.id.imageBanner2);
	           if (position==0) {
		            // do header stuff...
		    		
		    		 
		        	  wv.loadUrl("file:///android_asset/gif.html");
		        	  LinearLayout ln =(LinearLayout)MyView.findViewById(R.id.ListItem);
		        	  ln.getLayoutParams().height=0;
		        	  return MyView;
		         }
	           wv.getLayoutParams().height =0;
	           //wv.setLayoutParams(params)
	           // Add The Text!!!
	           TextView tv = (TextView)MyView.findViewById(R.id.list_item_text);
	           //ShowLog.showLogDebug("THUNA", list.get(position).get("brief").toString());
	           if(list.get(position).get("brief") == null)
	           {
	        	   tv.setText("None");
	           }
	           else
	           {
	        	   tv.setText(list.get(position).get("brief").toString());
	           }
	           
	           
	           TextView txtTitle = (TextView)MyView.findViewById(R.id.title);
	           if(list.get(position).get("title") == null)
	           {
	        	   txtTitle.setText("None");
	           }
	           else
	           {
	        	   txtTitle.setText(list.get(position).get("title").toString());
	           }
	           
	           // Add The Image!!!           
	           final ImageButton iv = (ImageButton)MyView.findViewById(R.id.list_item_image);
	           iv.setImageBitmap(getImageBitmap(Constant.ROOT_ANDROID+ list.get(position).get("image").toString()));
	           iv.setId(position);
	          // Log.d("linhnv","====================== image id:"+ iv.getId()+"===link :"+list.get(iv.getId()).get("url"));
	           iv.setOnClickListener(new OnClickListener() {
					
					public void onClick(View v) {
						// Play video
						
						Log.d("linhnv","===================onbtn click");
//						Intent intent = new Intent(mContext, VideoViewPlay.class);
//				    	mContext.startActivity(intent);
						String url = list.get(iv.getId()).get("url");
						mContext.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(url)));//"rtsp://14.0.19.168/Alvinandthechipmunks.mp4")));
						
					}
			});
	           
	        }
	        
	        return MyView;
	    }
	    private Bitmap getImageBitmap(String url) { 
            Bitmap bm = null; 
            try { 
                URL aURL = new URL(url); 
                URLConnection conn = aURL.openConnection(); 
                conn.connect(); 
                InputStream is = conn.getInputStream(); 
                BufferedInputStream bis = new BufferedInputStream(is); 
                bm = BitmapFactory.decodeStream(bis); 
                bis.close(); 
                is.close(); 
           } catch (IOException e) { 
               Log.e("Linhnv", "Error getting bitmap", e); 
           } 
           
//			try {
//				 HttpGet httpRequest = null;
//				try {
//					httpRequest = new HttpGet(new URL(url).toURI());
//				} catch (URISyntaxException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//				 HttpClient httpClient = new DefaultHttpClient();
//				 HttpResponse response;
//				response = (HttpResponse) httpClient.execute(httpRequest);
//				HttpEntity entity = response.getEntity();
//	            BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); 
////	            final long contentLength = bufHttpEntity.getContentLength();
//	            InputStream is = bufHttpEntity.getContent();
//	            bm = BitmapFactory.decodeStream(is);
//			} catch (ClientProtocolException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
            

           return bm; 
        } 
	    	
	    private Uri url=Uri.parse("http://android.kenhphimviet.com/images/film_le/22bullets.jpg") ;
	    // references to our images
	    private Integer[] mThumbIds = {
	            R.drawable.sample_0, R.drawable.sample_0,
	            R.drawable.sample_0, R.drawable.sample_0,
	            R.drawable.sample_0, R.drawable.sample_0,
	            R.drawable.sample_0, R.drawable.sample_0,
	            R.drawable.sample_0, R.drawable.sample_0,
	            R.drawable.sample_0, R.drawable.sample_0,
	            R.drawable.sample_0, R.drawable.sample_0,
	            R.drawable.sample_0, R.drawable.sample_0,
	            R.drawable.sample_0, R.drawable.sample_0,
	            R.drawable.sample_0, R.drawable.sample_0,
	            R.drawable.sample_0, R.drawable.sample_0
	    };
	    private Uri[] mThumbIds2 = {
	    		url, url,
	    		url, url,
	    		url, url,
	    		url, url,
	    		url, url,
	    		url, url,
	    		url, url,
	    		url, url,
	    		url, url,
	    		url, url,
	    		url,url
	    };
	   private void loadData()
	   {
		   HttpCommunication httpComm = new HttpCommunication();
			
			// Set path for XML
	    	httpComm.setUrl(typeDB + ".xml");
	    	InputStream inputStream = httpComm.get();
	    	
	    	if(null == inputStream){
	    		ShowLog.showLogDebug("ThuNa", "InputStream from URL is null");
	    	}
	    	
	    	ParseXMLAccess parserXML = new ParseXMLAccess();
	    	parserXML.setDataSourceInputStream(inputStream, Constant.ROOT_TAG);
	    	if(list != null && !list.isEmpty())
	    	{
	    		list.clear();
	    	}
	    	list = parserXML.getData();
	    	
	    	if(list == null || list.size() == 0)
	    	{
	    		
	    	}
//	    	ShowLog.showLogDebug("THUNA", list.get(0).get("id").toString());
//	    	Log.d("Linhnv","======================================="+list.get(0).get("image").toString());
	    }
	
}
